﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OurMind.Controls.Primitives
{
    ///<summary>将原来的 Reset Action 改为了替换源信息。</summary>
    internal class CollectionChangedListener<T>
    {
        private IEnumerable<T> _source;

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public void SetSource(IEnumerable<T> newObj)
        {
            UnloadOld(_source);
            LoadNew(newObj);
            CollectionChanged?.Invoke(newObj, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        private void LoadNew(IEnumerable<T> newObj)
        {
            _source = newObj;
            if (newObj == null) return;
            if (newObj is INotifyCollectionChanged notifyObj)
                notifyObj.CollectionChanged += SourceCollectionChanged;
        }

        private void UnloadOld(IEnumerable<T> oldObj)
        {
            if (_source == null) return;
            if (oldObj is INotifyCollectionChanged notifyObj)
                notifyObj.CollectionChanged -= SourceCollectionChanged;
        }

        private void SourceCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            CollectionChanged?.Invoke(sender, e);
        }

    }
}
